package com.opta.thread;

/**
 * 2 * @Author: GuanChong
 * 3 * @Date: 2020/9/28 10:54
 * 4
 */
public  class ReadThread implements Runnable {
    public Thread t;
    private String threadName;
    boolean suspended = false;
    private Integer stopTime;

    public ReadThread(String threadName, Integer stopTime) {
        this.threadName = threadName;
        this.stopTime = stopTime;
        System.out.println("Creating " + threadName);
        System.out.println("Creating " + stopTime);
    }

    @Override
    public void run() {
        for (int i = stopTime; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
//            if(i <=90){
//                this.t.interrupt();
//                break;
//            }
            // Let the thread sleep for a while.
            try {
                Thread.sleep(1000);
                synchronized (this) {
                    while (suspended) {
                        wait();
                    }
                }
            } catch (InterruptedException e) {
                System.out.println("Thread " + threadName + " interrupted.");
                e.printStackTrace();
            }
            System.out.println("Thread " + threadName + " exiting.");
        }
    }

    /**
     * 开始
     */
    public void start() {
        System.out.println("Starting " + threadName);
        if (t == null) {
            t = new Thread(this, threadName);
            t.start();
        }
    }

    /**
     * 暂停
     */
    public void suspend() {
        suspended = true;
    }

    /**
     * 继续
     */
    public synchronized void resume() {
        suspended = false;
        notify();
    }



    public static void main(String[] args) {


        ReadThread readThread = new ReadThread("opta1", 100);
        System.out.println("线程开始");
        readThread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程暂停");
        readThread.suspend();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程继续");
        readThread.resume();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}